﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Timers;
using System.Windows.Forms;

namespace TestEchart
{
	public partial class Form2 : Form
	{
		private SimpleHttpServer _httpServer;
		private readonly string[] _prefixes = {
			"http://localhost:8008/",
			"http://localhost:8008/dataPosition/",
		};
		public Form2()
		{
			InitializeComponent();
		}

		//private async void InitializeWebView2()
		//{
		//    try
		//    {
		//        await webView21.EnsureCoreWebView2Async().ConfigureAwait(false);
		//    }
		//    catch (Exception ex)
		//    {
		//    }

		//    var s = $"file:///{Application.StartupPath}/line2.html".Replace("\\", "/");
		//    var s1 = $"file:///{Application.StartupPath}/bar.html".Replace("\\", "/");
		//    webView21.Source = new Uri(s);
		//    webView22.Source = new Uri(s1);
		//}




		private void Form2_Load(object sender, EventArgs e)
		{
			var s = $"{Application.StartupPath}\\line2.html";
			s = "file:///" + Uri.EscapeDataString(s).Replace("\\", "/");

			var s1 = $"{Application.StartupPath}\\bar.html";
			s1 = "file:///" + Uri.EscapeDataString(s1).Replace("\\", "/");

			webView21.Source = new Uri(s);
			webView22.Source = new Uri(s1);

			_httpServer = new SimpleHttpServer(_prefixes);
			_httpServer.RequestReceived += ProcessRequest;
			var serverThread = new Thread(() => _httpServer.Start());
			serverThread.Start();
			timer1.Start();

		}

		private readonly Random _random = new Random(DateTime.Now.Millisecond);
		private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
		{
			var name = $"{Application.StartupPath}\\data.json";
			var ls = new List<object>();
			var lineData = new LineData
			{
				X = new double[100],
				Y = new double[100]
			};
			for (var i = 0; i < 100; i++)
			{
				lineData.X[i] = i;
				lineData.Y[i] = _random.Next(1000) / 10.0;
			}
			lineData.Avg = lineData.Y.Average();
			ls.Add(lineData);
			var js = JsonSerializer.Serialize(ls);
			for (var i = 0; i < 3; i++)
			{
				try
				{
					File.WriteAllText(name, js);
					break;
				}
				catch
				{
					Application.DoEvents();
				}
			}

		}
		private void ProcessRequest(object sender, HttpListenerContext context)
		{
			var request = context.Request;
			var response = context.Response;
			response.Headers.Add("Access-Control-Allow-Origin", "*");//重点
			response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
			response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
			if (request.HttpMethod == "OPTIONS")
			{
				// 处理预检请求
				response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
				response.StatusCode = (int)HttpStatusCode.NoContent; // 204 No Content
				response.Close();
				return;

			}
			if (request.HttpMethod == "POST")
			{
				if (request.Url.LocalPath == "/dataPosition")
				{
					if (request.ContentType != null && request.ContentType.Contains("application"))
					{
						using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
						{
							var json = reader.ReadToEnd();
							Debug.WriteLine("接收到鼠标位置: " + json);
							Invoke((Action)(() =>
							{
								label1.Text = @"接收到鼠标位置: " + json;
							}));
						}

						response.StatusCode = (int)HttpStatusCode.OK;
						response.Close();
						return;
					}
				}
			}

			var filePath = GetFilePath(request.Url.LocalPath);

			if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
			{

				response.StatusCode = (int)HttpStatusCode.NotFound;
				response.Close();
				return;
			}
			string[] _allowedExtensions = { ".json" };
			var extension = Path.GetExtension(filePath);
			if (!_allowedExtensions.Contains(extension))
			{
				response.StatusCode = (int)HttpStatusCode.Forbidden;
				response.Close();
				return;
			}
			var fileBytes = File.ReadAllBytes(filePath);
			response.ContentType = "application/json";
			response.ContentEncoding = Encoding.UTF8;
			response.ContentLength64 = fileBytes.Length;
			response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
			response.OutputStream.Close();
		}

		private string GetFilePath(string urlPath)
		{
			var filePath = urlPath.TrimStart('/');
			filePath = Path.Combine(Application.StartupPath, filePath);
			return filePath;
		}

		private void Form2_FormClosed(object sender, FormClosedEventArgs e)
		{
			Environment.Exit(0);
		}
	}

	public class LineData
	{
		public double[] X { get; set; }
		public double[] Y { get; set; }
		public double Avg { get; set; }

	}

}